//数组转树形结构
export function toTree(data) {
    var treeArr = [];
    var treeList = [];
    var o;
    for (var i = 0; i < data.length; i++) {
        if (data[i].pid == 0 && data[i].type == 0) {
            treeArr.push(data[i])
        } else {
            treeList.push(data[i])
            o = Tree(treeList)
        }
    }
    if (treeArr.length > 0) {
        for (var i = 0; i < treeArr.length; i++) {
            for (var j = 0; j < o.length; j++) {
                if (treeArr[i].id == o[j].pid) {
                    treeArr[i].children = [];
                    treeArr[i].children.push(o[j])
                }
            }
        }
        return treeArr
    } else {
        return o
    }
}

export function Tree(data) {
    // 删除 所有 children,以防止多次调用
    data.forEach(function (item) {
        delete item.children;
    });
    // 将数据存储为 以 id 为 KEY 的 map 索引数据列
    var map = {};
    data.forEach(function (item) {
        map[item.id] = item;
    });
    var val = [];
    data.forEach(function (item) {
        // 以当前遍历项，的pid,去map对象中找到索引的id
        var parent = map[item.pid];
        // 如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
        if (parent) {
            (parent.children || (parent.children = [])).push(item);
        } else {
            //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
            val.push(item);
        }
    });
    return val;
}

export function fsdmTree(data) {
    // 删除 所有 children,以防止多次调用
    data.forEach(function (item) {
        delete item.children;
    });
    // 将数据存储为 以 id 为 KEY 的 map 索引数据列
    var map = {};
    data.forEach(function (item) {
        map[item.taskId] = item;
    });
    var val = [];
    data.forEach(function (item) {
        // 以当前遍历项，的pid,去map对象中找到索引的id
        var parent = map[item.parentId];
        // 如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
        if (parent) {
            (parent.children || (parent.children = [])).push(item);
        } else {
            //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
            val.push(item);
        }
    });
    return val;
    // console.log(val)
}

export function docTree(data) {
    // 删除 所有 children,以防止多次调用
    data.forEach(function (item) {
        delete item.children;
    });
    // 将数据存储为 以 fileId 为 KEY 的 map 索引数据列
    var map = {};
    data.forEach(function (item) {
        map[item.fileId] = item;
    });
    var val = [];
    data.forEach(function (item) {
        // 以当前遍历项，的pid,去map对象中找到索引的id
        var parent = map[item.pid];
        // 如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
        if (parent) {
            (parent.children || (parent.children = [])).push(item);
        } else {
            //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
            val.push(item);
        }
    });
    return val;
}

//改变树结构里面的KEY
export function trans(data) {
    data.forEach(obj => {
        obj.title = obj.name
        obj.label = obj.name
        //  if(obj.dirId){
        //   obj.id = obj.dirId
        //  }
        obj.id = obj.id || obj.taskId || obj.dirId || obj.partId || obj.planId || obj.areaId || 0;

        if (obj.children instanceof Array) {
            trans(obj.children)
        }
    })
    return data
}
//改变树结构里面的KEY
export function transs(data, id) {
    data.forEach(obj => {
        obj.title = obj.name || obj.monTypeName
        obj.label = obj.name || obj.monTypeName
        obj.name = obj.name || obj.monTypeName
        obj.children = obj.monTypeList || obj.pointList
        if ((obj.monTypeList || obj.pointList) instanceof Array) {
            transs((obj.monTypeList || obj.pointList))
        }
    })
    return data
}
//改变管网树结构里面的key
export function pipeTrans(data) {
    data.forEach(obj => {
        obj.title = obj.workAreaName || obj.parentName || obj.pipeName || '';
        obj.label = obj.workAreaName || obj.parentName || obj.pipeName || '';
        obj.id = obj.workAreaId || obj.parentId || obj.pipeId || 0;
        if (obj.children instanceof Array) {
            pipeTrans(obj.children)
        }
    })
    return data
}
//改变质量与安全树结构里面的KEY
export function transId(data) {
    data.forEach(obj => {
        obj.id = obj.partId || obj.issueTypeId
        obj.title = obj.name
        obj.label = obj.name
        if (obj.children instanceof Array) {
            transId(obj.children)
        }
    })
    return data
}
export function setIssueTree(data) {
    data.forEach(obj => {
        obj.id = obj.issueId ? obj.issueId : obj.issueTypeId;
        obj.title = obj.content ? obj.content : obj.name;
        obj.label = obj.content ? obj.content : obj.name;
        obj.children = obj.children || obj.issues;
        if (obj.issueId) {
            obj.isDisabled = obj.enableFlag == 0 ? true : false;
        }
        if (obj.children instanceof Array) {
            setIssueTree(obj.children)
        }
    })
    return data
}

export function checked(data, list) {
    for (let i in list) {
        for (let j in data) {
            if (list[i] == data[j].id && (data[j].children.length == 0 || !data[j].children)) {
                data[j].checked = true;
            } else {
                checked(data[j].children, list)
            }
        }
    }
    return data;
}

export function check(data, list) {
    for (let i = 0; i < list.length; i++) {
        for (let j of data) {
            if (list[i] == j.id && !j.children) {
                j.checked = true;
            } else {
                check(j.children, list)
            }
        }
    }
    return data;
}

export function unselect(data) {
    for (let i of data) {
        i.checked = false;
        unselect(i.children)
    }
    return data;
}


//树形结构转换为扁平数组
export function flatten(tree) {
    var queen = [];
    var out = [];
    queen = queen.concat(tree);
    while (queen.length) {
        var first = queen.shift();
        if (first.children) {
            queen = queen.concat(first.children)
            delete first['children'];
        }

        out.push(first);
    }
    return out;
}

export function transTree(data) {
    data.forEach(obj => {
        obj.title = obj.name
        // delete obj["name"]
        if (obj.children instanceof Array) {
            trans(obj.children)
        }
    })
    return data
}

export function newTree(o) {
    const x = [];
    const map = o.reduce((x, v) => ((x[v.id] = v), x), {});
    for (const item of o) {
        if (item.pid === 0) {
            x.push(item);
            continue;
        }
        if (item.pid in map) {
            const parent = map[item.pid];
            parent.children = parent.children || [];
            parent.children.push(item);
        }
    }
    return o;
}

//找出两个数组中不同的数据
export function getArrDifference(arr1, arr2) {
    let newArr = [];
    arr1.forEach((itm) => {
        let itmStr = itm.toString();
        let temp = arr2.every(ele => itmStr !== ele.toString());
        if (temp) {
            newArr.push(itm);
        }
    });
    arr2.forEach((itm) => {
        let itmStr = itm.toString();
        let temp = arr1.every(ele => itmStr !== ele.toString());
        if (temp) {
            newArr.push(itm);
        }
    });
    return newArr;
}

export function getNoChild(arr1, arr2) {
    let newArr = [];
    for (let i in arr1) {
        for (let j in arr2) {
            if (arr1[i] == arr2[j].id) {
                for (let s in arr2[j].children) {
                    if (arr2[j].children[s].children.length > 0) {
                        for (let k in arr2[j].children[s].children) {
                            if (arr2[j].children[s].children[k].checked == true) {
                                newArr.push(arr2[j].children[s].id)
                                newArr.push(arr2[j].id)
                            }
                        }
                    } else {
                        if (arr2[j].children[s].checked == true) {
                            newArr.push(arr2[j].id)
                        }
                    }
                }
            }
        }
    }
    return newArr;
}

//去掉数组中重复的对象
export function uniqObjInArray(objarray) {
    let len = objarray.length;
    let tempJson = {};
    let res = [];
    for (let i = 0; i < len; i++) {
        //取出每一个对象
        tempJson[JSON.stringify(objarray[i])] = true;
    }
    let keyItems = Object.keys(tempJson);
    for (let j = 0; j < keyItems.length; j++) {
        res.push(JSON.parse(keyItems[j]));
    }
    return res;
}

export function getTreeData(data) {
    let arr = [];
    data.forEach(i => {
        if (i.pid == 0) {
            let obj = {
                title: i.title,
                path: i.path,
                id: i.id,
                pid: i.pid,
                children: [],
                checked: i.checked
            }
            arr.push(obj);
        }
    })
    arr.forEach(i => {
        data.forEach(j => {
            if (i.id == j.pid) {
                let obj = {
                    title: j.title,
                    path: j.path,
                    id: j.id,
                    pid: j.pid,
                    children: [],
                    checked: j.checked
                };
                i.children.push(obj)
            }
        })
    })
    for (let i in arr) {
        for (let j in arr[i].children) {
            for (let k in data) {
                if (arr[i].children[j].id == data[k].pid) {
                    let obj2 = {
                        title: data[k].title,
                        path: data[k].path,
                        id: data[k].id,
                        pid: data[k].pid,
                        children: [],
                        checked: data[k].checked
                    };
                    arr[i].children[j].children.push(obj2);
                }
            }
        }
    }
    for (let i in arr) {
        if (arr[i].checked == true && (arr[i].children.length == 0 || !arr[i].children)) {
            arr[i].checked = true;
        } else {
            arr[i].checked = false;
            for (let j in arr[i].children) {
                if (arr[i].children[j].checked == true && (arr[i].children[j].children.length == 0 || !arr[i].children[j].children)) {
                    arr[i].children[j].checked = true;
                } else {
                    arr[i].children[j].checked = false;
                }
            }
        }
    }
    return arr;
}

export function RChildren(data) {
    for (let i in data) {
        if (data[i].children.length == 0) {
            delete data[i].children;
        } else {
            for (let j in data[i].children) {
                if (data[i].children[j].children.length == 0) {
                    delete data[i].children[j].children
                } else {
                    for (let k in data[i].children[j].children) {
                        if (data[i].children[j].children[k].children.length == 0) {
                            delete data[i].children[j].children[k].children
                        }
                    }
                }
            }
        }
    }
    return data
}


export function selTreeName(data, id) {
    var hasFound = false, // 表示是否有找到id值
        result = null;
    var fn = function (data) {
        if (Array.isArray(data) && !hasFound) { // 判断是否是数组并且没有的情况下，
            data.forEach(item => {
                if (item.id === id) { // 数据循环每个子项，并且判断子项下边是否有id值
                    result = item; // 返回的结果等于每一项
                    hasFound = true; // 并且找到id值
                } else if (item.children) {
                    fn(item.children); // 递归调用下边的子项
                }
            })
        }
    }
    fn(data); // 调用一下
    return result.name;
}

export function selTreeUrl(data, name) {
    // eslint-disable-next-line one-var
    var hasFound = false, // 表示是否有找到id值
        result = null
    var fn = function (data) {
        if (Array.isArray(data) && !hasFound) { // 判断是否是数组并且没有的情况下，
            data.forEach(item => {
                // eslint-disable-next-line no-undef
                if (item.name === name) { // 数据循环每个子项，并且判断子项下边是否有id值
                    result = item // 返回的结果等于每一项
                    hasFound = true // 并且找到id值
                } else if (item.children) {
                    fn(item.children) // 递归调用下边的子项
                }
            })
        }
    }
    fn(data) // 调用一下
    return result.url
}

/**
 * 递归将选项中的 value 值及其 children 里面的 value 都转换成数字类型
 *
 * @param {Array} options 选项，格式为: [{ value: 0, label: "", children: [{ value: 2, label: "" }] }]
 */
export function parseValueToInt(options) {
    options.forEach(opt => {
        opt.value = parseInt(opt.value);
        if (opt.children && opt.children.length > 0) {
            parseValueToInt(opt.children);
        }
    });
}


export function GetAge(strBirthday) {
    var returnAge;
    var strBirthdayArr = strBirthday.split("-");
    var birthYear = strBirthdayArr[0];
    var birthMonth = strBirthdayArr[1];
    var birthDay = strBirthdayArr[2];
    var d = new Date();
    var nowYear = d.getFullYear();
    var nowMonth = d.getMonth() + 1;
    var nowDay = d.getDate();
    if (nowYear == birthYear) {
        returnAge = 0; //同年 则为0岁
    } else {
        var ageDiff = nowYear - birthYear; //年之差
        if (ageDiff > 0) {
            if (nowMonth == birthMonth) {
                var dayDiff = nowDay - birthDay; //日之差
                if (dayDiff < 0) {
                    returnAge = ageDiff - 1;
                } else {
                    returnAge = ageDiff;
                }
            } else {
                var monthDiff = nowMonth - birthMonth; //月之差
                if (monthDiff < 0) {
                    returnAge = ageDiff - 1;
                } else {
                    returnAge = ageDiff;
                }
            }
        } else {
            returnAge = -1; //返回-1 表示出生日期输入错误 晚于今天
        }
    }
    return returnAge; //返回周岁年龄
}

export function urlencode(str) {
    str = (str + '').toString();

    return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}

export function selTreelist(data, id) {
    var hasFound = false,
        result = null;
    var fn = function (data) {
        if (Array.isArray(data) && !hasFound) {
            data.forEach(item => {
                if (item.id === id) {
                    result = item;
                    hasFound = true;
                } else if (item.children) {
                    fn(item.children);
                }
            })
        }
    }
    fn(data);
    return result;
}

export function deteleObject(obj) {
    var uniques = [];
    var stringify = {};
    for (var i = 0; i < obj.length; i++) {
        var keys = Object.keys(obj[i]);
        keys.sort(function (a, b) {
            return (Number(a) - Number(b));
        });
        var str = '';
        for (var j = 0; j < keys.length; j++) {
            str += JSON.stringify(keys[j]);
            str += JSON.stringify(obj[i][keys[j]]);
        }
        if (!stringify.hasOwnProperty(str)) {
            uniques.push(obj[i]);
            stringify[str] = true;
        }
    }
    uniques = uniques;
    return uniques;
}

// 排序
export function bubbleSort(arr) {
    var len = arr.length;
    for (var i = 0; i < len; i++) {
        for (var j = 0; j < len - 1 - i; j++) {
            if (arr[j].index > arr[j + 1].index) { //相邻元素两两对比
                var temp = arr[j + 1]; //元素交换
                arr[j + 1] = arr[j];
                arr[j] = temp;
            }
        }
    }
    return arr;
}


export function getWeekDay(date) {
    // var date = 2016-8-10;//日期为输入日期，格式为 2016-8-10
    var array = date.split('-');
    var date = new Date(array[0], parseInt(array[1]) - 1, array[2]);
    var weekArray = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
    var weekDay = weekArray[date.getDay()];
    return weekDay;
}

export function toPercent(point) {
    var str = Number(point * 100).toFixed(1);
    str += "%";
    return str;
}

export function toPercentCopy(point) {
    var str = Number(point * 100).toFixed(2);
    str += "%";
    return str;
}


export function formatDate(num, format) {
    const formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
    const returnArr = [];
    const date = new Date(num);
    returnArr.push(date.getFullYear()); // 取得4位数的年份
    returnArr.push(formatNumber(date.getMonth() + 1)); // 取得日期中的月份，其中0表示1月，11表示12月
    returnArr.push(formatNumber(date.getDate())); // 返回日期月份中的天数（1到31）
    returnArr.push(formatNumber(date.getHours())); // 返回日期中的小时数（0到23）
    returnArr.push(formatNumber(date.getMinutes())); // 返回日期中的分钟数（0到59）
    returnArr.push(formatNumber(date.getSeconds())); // 返回日期中的秒数（0到59）
    for (const i in returnArr) {
        // 判断对象是否含有某个非继承属性
        if ({}.hasOwnProperty.call(returnArr, i)) {
            format = format.replace(formateArr[i], returnArr[i]); // 替换
        }
    }
    return format;
}

function formatNumber(n) {
    n = n.toString();
    return n[1] ? n : `0${n}`;
}

export function getQueryString() {
    let result;
    let code = window.location.href.split("?")[1];
    if (code.indexOf('&') > -1) {
        result = code.substring(5, code.indexOf("&"));

    } else {
        result = code.substring(5, code.length)
    }
    return result;
}

export function getUrlSearch(name) {
    // 未传参，返回空
    if (!name) return null;
    // 查询参数：先通过search取值，如果取不到就通过hash来取
    var after = window.location.search;
    after = after.substr(1) || window.location.hash.split('?')[1];
    // 地址栏URL没有查询参数，返回空
    if (!after) return null;
    // 如果查询参数中没有"name"，返回空
    if (after.indexOf(name) === -1) return null;

    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
    // 当地址栏参数存在中文时，需要解码，不然会乱码
    var r = decodeURI(after).match(reg);
    // 如果url中"name"没有值，返回空
    if (!r) return null;

    return r[2];
}

//树形结构排序
export function treeSort(arr) {
    var len = arr.length;
    for (var i = 0; i < len; i++) {
        if (arr[i].children && arr[i].children.length > 0) {
            treeSort(arr[i].children)
        }
        for (var j = 0; j < len - 1 - i; j++) {
            if (arr[j].index > arr[j + 1].index) { //相邻元素两两对比
                var temp = arr[j + 1]; //元素交换
                arr[j + 1] = arr[j];
                arr[j] = temp;
            }
        }
    }
    return arr;
}
